$(function() {
	//禁止F5刷新
  document.onkeydown = function(e) {
      e = window.event || e;
      var keycode = e.keyCode || e.which;
      if (keycode = 116) {
        if (window.event) { // ie
          e.keyCode ? e.keyCode = 0 : e.which = 0;
          return false;
        } else { // ff
          e.preventDefault();
        }
      }
    }
  //禁止右键
  document.oncontextmenu = function(e) {
    return false;
  }
  //转换字符串为JSON对象
  var strToJson=function(str){
  	return eval("("+str+")");
  };

  //点击连接阅读器
  $('#btnConn').on('click', '', function() {
    open();
  });

  //获取连接状态
  $('#btnGetStatus').on('click','',function(){
  	var ret=CertCtl.getStatus();
  	setResult(ret);
  });

  //读身份证
  $('#btnRead').on('click','',function(){
  	open();
  	var ret=CertCtl.readCert();
  	setResult(ret);
  	close();
  });

  //点击关闭连接
  $('#btnClose').on('click','',function(){
  	var ret=close();
  	setResult(ret);
  });

  //打开连接
  var open=function(){
  	var ret = CertCtl.connect();
    setResult(ret);
  };

  //关闭连接
  var close=function(){
  	var ret=CertCtl.disconnect();
  	return ret;  	
  }

  //设置结果显示
  var setResult=function(ret){
  	$('#result').html(ret);
  	ret=strToJson(ret);
  	if(ret.resultFlag===0){
  		$('#result').removeClass('warn');
  		$('#result').addClass('succ');
  	}
  	else{
  		$('#result').removeClass('succ');
  		$('#result').addClass('warn');
  	}
  	$('#IdCard')[0].reset();
  	$('#IdCard').find('image').attr('src','');
  	//如果有读取到身份证，填充页面身份证信息
  	if(ret.resultContent){
  		ret.resultContent.sex=ret.resultContent.gender===1?'男':'女';
  		$('#IdCard').find('input').each(function(){
  			$(this).val(ret.resultContent[$(this).attr('id')]);
  		});
  		$('#IdCard').find('image').each(function(){
  			$(this).attr('src','data:image/jpg;base64,' + ret.resultContent[$(this).attr('id')]);
  		});
  	}
  };
});
